package com.xh.bussiness.thirdapi.feihong.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class JSONPUtils {

    /**
     * 往爱校发送JSONP POST请求
     *
     * */
    @SuppressWarnings("rawtypes")
    public static Map jsonp(Map<String, String> map , String url) {
        System.out.println(url + "?" + getUrlStr(map));
        Map<String, Object> reMap = new HashMap<String, Object>();
        try{
            if(map.size() == 0){
                reMap.put("outResult", "0");
                reMap.put("outResultReason", "无数据需要发送");
                return reMap;
            }

            HttpClient client = new HttpClient();
            //返回结果集
            JSONObject resJson = new JSONObject();

            UTF8PostMethod postMethod = new UTF8PostMethod(url);
            client.getParams().setSoTimeout(30000);
            for(Map.Entry<String, String> entry : map.entrySet()){
                postMethod.setParameter(entry.getKey().trim(), entry.getValue().trim());
            }
            //执行请求，返回状态码
            int status = client.executeMethod(postMethod);
            if (status == HttpStatus.SC_OK) {
                InputStream is = postMethod.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
                StringBuffer sb = new StringBuffer();
                String str = "";
                if ((str = br.readLine()) != null) {
                    sb.append(str);
                }
                String result = sb.toString();
                reMap.put("currentTime", Calendar.getInstance().getTime());
                if("".equals(result) || result == null) {
                    reMap.put("outResult", "0");
                    reMap.put("outResultReason", "请求成功，但返回数据为空！");
                    return reMap;
                }
                //String s = result.replaceAll("\\[", "").replaceAll("\\]", "");
                //resJson = JSONObject.fromObject(result);

                /*Iterator iterator = resJson.keys();
                String key = null;
                String value = null;

                while(iterator.hasNext()){
                 	key = (String) iterator.next();
                    value = resJson.getString(key);
                    reMap.put(key,value);
                }*/
                JSONArray jsonObject = JSONArray.parseArray(result);
                reMap.put("data",jsonObject);
            } else {
//            	接口请求失败。
                reMap.put("outResult", "0");
                reMap.put("outResultReason", "请求失败。错误码"+status);
            }
        }catch(Exception e){
            reMap.put("outResult", "0");
            reMap.put("outResultReason", "请求超时。");
        }
        return reMap;
    }

    /**
     *发送post请求
     * @param url
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static Map httpPost(String url) {
        Map<String, Object> reMap = new HashMap<String, Object>();
        try{
            HttpClient client = new HttpClient();
            //返回结果集
            JSONObject resJson = new JSONObject();

            UTF8PostMethod postMethod = new UTF8PostMethod(url);

            client.getParams().setSoTimeout(30000);
            //执行请求，返回状态码
            int status = client.executeMethod(postMethod);
            if (status == HttpStatus.SC_OK) {
                String result = postMethod.getResponseBodyAsString();

                reMap.put("currentTime",  Calendar.getInstance().getTime());
                if("".equals(result) || result == null)
                {
                    reMap.put("outResult", "0");
                    reMap.put("outResultReason", "请求成功，但返回数据为空！");
                    return reMap;
                }
                resJson = JSONObject.parseObject(result);

                Iterator iterator = resJson.keySet().iterator();
                String key = null;
                String value = null;

                while(iterator.hasNext()){
                    key = (String) iterator.next();
                    value = resJson.getString(key);
                    reMap.put(key,value);
                }

            } else {
//            	接口请求失败。
                reMap.put("outResult", "0");
                reMap.put("outResultReason", "请求失败。错误码"+status);
            }
        }catch(Exception e){
            reMap.put("outResult", "0");
            reMap.put("outResultReason", "请求超时。");
        }
        return reMap;
    }


    /**
     * 短信调用接口
     * @param map
     * @param url
     * @return
     * @throws IOException
     * @throws HttpException
     */
    public static String httpPost(Map<String, String> map , String url) throws HttpException, IOException {
        if(map.size() == 0){
            return "参数不能为空";
        }
        HttpClient client = new HttpClient();

        UTF8PostMethod postMethod = new UTF8PostMethod(url);

        client.getParams().setSoTimeout(30000);
        for(Map.Entry<String, String> entry : map.entrySet()){
            postMethod.setParameter(entry.getKey().trim(), entry.getValue().trim());
        }
        //执行请求，返回状态码
        int status = client.executeMethod(postMethod);
        if (status == HttpStatus.SC_OK) {
            String result = postMethod.getResponseBodyAsString();

            if("".equals(result) || result == null)
            {
                return "请求成功，但返回数据为空！";
            }
            return "请求成功: "+result;
        } else {
            return "请求失败！";
        }
    }

    public static String getUrlStr(Map<String, String> params) {
        // 遍历排序后的字典，将所有参数按"key=value"格式拼接在一起
        StringBuilder baseString = new StringBuilder();
        for (Map.Entry<String, String> item : params.entrySet()) {
            String key = item.getKey();
            String value = item.getValue();
            if (!StringUtils.isEmpty(key) && !StringUtils.isEmpty(value)) {
                baseString.append(key + "=" + value + "&");
            } else if (!StringUtils.isEmpty(key)) {
                baseString.append(key);
            }
        }
        return baseString.toString();
    }
}
